import { api } from '@/utils/request'

// 曝光台相关接口类型定义
export interface ExposureStats {
  total_posts: number
  today_posts: number
  total_comments: number
  total_likes: number
}

export interface ExposurePost {
  id: string
  user_id: string
  content: string
  images: string[]
  like_count: number
  comment_count: number
  share_count: number
  created_at: string
  updated_at: string
  users: {
    id: string
    nickname: string
    avatar_url?: string
    phone_number?: string
  }
  exposure_comments?: ExposureComment[]
}

export interface ExposureComment {
  id: string
  post_id: string
  user_id: string
  content: string
  created_at: string
  users: {
    id: string
    nickname: string
  }
}

// 管理员登录接口
export interface LoginParams {
  username: string
  password: string
}

export interface LoginResponse {
  admin: {
    id: number
    username: string
    created_at: string
    updated_at: string
  }
  token: string
}

export interface ApiResponse<T = any> {
  success: boolean
  message: string
  data: T
}

export interface PaginatedResponse<T = any> {
  success: boolean
  message: string
  data: T[]
  pagination: {
    page: number
    pageSize: number
    total: number
    totalPages: number
  }
}

// 统计数据接口
export interface DashboardStats {
  users: {
    total: number
    active: number
    today: number
  }
  listings: {
    total: number
    active: number
    today: number
  }
  orders?: {
    total: number
    today: number
  }
  revenue?: {
    total: number
    today: number
  }
}

// 管理员相关API
export const adminApi = {
  // 登录
  login: (params: LoginParams): Promise<ApiResponse<LoginResponse>> => {
    return api.post('/admin/login', params)
  },

  // 获取当前管理员信息
  getCurrentAdmin: (): Promise<ApiResponse> => {
    return api.get('/admin/me')
  },

  // 获取仪表盘统计数据
  getDashboardStats: (): Promise<ApiResponse<DashboardStats>> => {
    return api.get('/admin/dashboard/stats')
  }
}

// 用户管理API
export type ResourceIdentifier = number | string

export interface User {
  id: ResourceIdentifier
  openid: string
  nickname?: string
  avatar_url?: string
  phone_number?: string
  wechat_id?: string
  status: 'inactive' | 'active'
  chat_banned: boolean
  publishing_credits: number
  chat_credits: number
  contact_view_credits: number
  local_service_credits: number
  inviter_id?: number
  created_at: string
  updated_at: string
}

export interface UserListParams {
  page?: number
  pageSize?: number
  status?: 'inactive' | 'active'
  search?: string
}

export const userApi = {
  // 获取用户列表
  getList: (params: UserListParams): Promise<PaginatedResponse<User>> => {
    return api.get('/admin/users', { params })
  },

  // 获取用户详情
  getDetail: (id: ResourceIdentifier): Promise<ApiResponse<User>> => {
    return api.get(`/admin/users/${id}`)
  },

  // 更新用户状态
  updateStatus: (id: ResourceIdentifier, status: 'inactive' | 'active'): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/status`, { status })
  },

  // 更新用户发布额度
  updateCredits: (id: ResourceIdentifier, credits: number): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/credits`, { credits })
  },

  // 减少用户发布额度
  reduceCredits: (id: ResourceIdentifier, credits: number): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/reduce-credits`, { credits })
  },

  // 更新用户聊天信用
  updateChatCredits: (id: ResourceIdentifier, credits: number): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/chat-credits`, { credits })
  },

  // 减少用户聊天信用
  reduceChatCredits: (id: ResourceIdentifier, credits: number): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/reduce-chat-credits`, { credits })
  },

  // 更新用户查看联系方式信用
  updateContactViewCredits: (id: ResourceIdentifier, credits: number): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/contact-view-credits`, { credits })
  },

  // 减少用户查看联系方式信用
  reduceContactViewCredits: (id: ResourceIdentifier, credits: number): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/reduce-contact-view-credits`, { credits })
  },

  // 更新用户本地服务信用
  updateLocalServiceCredits: (id: ResourceIdentifier, credits: number): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/local-service-credits`, { credits })
  },

  // 减少用户本地服务信用
  reduceLocalServiceCredits: (id: ResourceIdentifier, credits: number): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/reduce-local-service-credits`, { credits })
  },

  // 禁言用户
  banChat: (id: ResourceIdentifier): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/ban-chat`)
  },

  // 解除禁言
  unbanChat: (id: ResourceIdentifier): Promise<ApiResponse> => {
    return api.put(`/admin/users/${id}/unban-chat`)
  }
}

// 挂牌信息管理API
export interface Listing {
  id: number
  user_id: number
  listing_type: '公司' | '个体户' | '代账户'
  company_name: string
  status: '在售' | '已售' | '下架'
  price?: number
  is_negotiable: boolean
  registration_province?: string
  registration_city?: string
  establishment_date?: string
  registered_capital_range?: string
  paid_in_status?: string
  company_type?: string
  tax_status?: string
  tax_grade?: string
  bank_account_status?: string
  has_trademark: boolean
  has_patent: boolean
  has_software_copyright: boolean
  has_license_plate: boolean
  // 审核相关字段
  audit_status: '待审核' | '已通过' | '已拒绝'
  audit_admin_id?: number
  audit_time?: string
  audit_comment?: string
  auto_publish_at?: string
  audit_admin?: {
    id: number
    username: string
  }
  has_social_security: boolean
  bank_flow?: string
  has_bidding_history: boolean
  description?: string
  expires_at?: string
  created_at: string
  updated_at: string
  user?: {
    nickname?: string
    phone_number?: string
  }
}

export interface ListingListParams {
  page?: number
  pageSize?: number
  status?: '在售' | '已售' | '下架' | ''
  listing_type?: '公司' | '个体户' | '代账户'
  search?: string
}

export const listingApi = {
  // 获取挂牌信息列表
  getList: (params: ListingListParams): Promise<PaginatedResponse<Listing>> => {
    return api.get('/admin/listings', { params })
  },

  // 获取挂牌信息详情
  getDetail: (id: number): Promise<ApiResponse<Listing>> => {
    return api.get(`/admin/listings/${id}`)
  },

  // 更新挂牌信息状态
  updateStatus: (id: number, status: '在售' | '已售' | '下架'): Promise<ApiResponse> => {
    return api.put(`/admin/listings/${id}/status`, { status })
  },

  // 删除挂牌信息
  delete: (id: number): Promise<ApiResponse> => {
    return api.delete(`/admin/listings/${id}`)
  },

  // 获取待审核列表
  getPendingAudit: (params: ListingListParams): Promise<PaginatedResponse<Listing>> => {
    return api.get('/admin/listings/pending-audit', { params })
  },

  // 审核通过
  approve: (id: number, comment?: string): Promise<ApiResponse<Listing>> => {
    return api.put(`/admin/listings/${id}/approve`, { comment })
  },

  // 审核拒绝
  reject: (id: number, comment: string): Promise<ApiResponse<Listing>> => {
    return api.put(`/admin/listings/${id}/reject`, { comment })
  },

  // 获取审核统计
  getAuditStats: (): Promise<ApiResponse<{
    pending: number
    approved: number
    rejected: number
    total: number
  }>> => {
    return api.get('/admin/listings/audit-stats')
  }
}

// 套餐管理API
export interface Package {
  id: number
  title: string
  description?: string
  price: number
  credits_amount: number
  package_type: 'paid' | 'chat_message' | 'contact_view' | 'local_service'
  is_active: boolean
  created_at: string
  updated_at: string
}

export interface PackageListParams {
  page?: number
  pageSize?: number
  is_active?: boolean
  package_type?: 'paid' | 'chat_message' | 'contact_view' | 'local_service'
  search?: string
}

export interface CreatePackageParams {
  title: string
  description?: string
  price: number
  credits_amount: number
  package_type?: 'paid' | 'chat_message' | 'contact_view' | 'local_service'
  is_active?: boolean
}

export interface UpdatePackageParams {
  title?: string
  description?: string
  price?: number
  credits_amount?: number
  package_type?: 'paid' | 'chat_message' | 'contact_view' | 'local_service'
  is_active?: boolean
}

export const packageApi = {
  // 获取套餐列表
  getList: (params: PackageListParams): Promise<PaginatedResponse<Package>> => {
    return api.get('/admin/packages', { params })
  },

  // 获取套餐详情
  getDetail: (id: number): Promise<ApiResponse<Package>> => {
    return api.get(`/admin/packages/${id}`)
  },

  // 创建套餐
  create: (params: CreatePackageParams): Promise<ApiResponse<Package>> => {
    return api.post('/admin/packages', params)
  },

  // 更新套餐
  update: (id: number, params: UpdatePackageParams): Promise<ApiResponse<Package>> => {
    return api.put(`/admin/packages/${id}`, params)
  },

  // 删除套餐
  delete: (id: number): Promise<ApiResponse> => {
    return api.delete(`/admin/packages/${id}`)
  },

  // 更新套餐状态
  updateStatus: (id: number, is_active: boolean): Promise<ApiResponse> => {
    return api.put(`/admin/packages/${id}/status`, { is_active })
  }
}

// 订单管理API
export interface Order {
  id: number
  order_number: string
  user_id: number
  package_id: number
  amount: number
  payment_status: 'pending' | 'paid' | 'failed' | 'cancelled'
  payment_method?: string
  payment_transaction_id?: string
  created_at: string
  updated_at: string
  user?: {
    nickname?: string
    phone_number?: string
  }
  package?: {
    title: string
    credits_amount: number
  }
}

export interface OrderListParams {
  page?: number
  pageSize?: number
  payment_status?: 'pending' | 'paid' | 'failed' | 'cancelled'
  search?: string
}

export const orderApi = {
  // 获取订单列表
  getList: (params: OrderListParams): Promise<PaginatedResponse<Order>> => {
    return api.get('/admin/orders', { params })
  },

  // 获取订单详情
  getDetail: (id: number): Promise<ApiResponse<Order>> => {
    return api.get(`/admin/orders/${id}`)
  },

  // 更新订单状态
  updateStatus: (id: number, payment_status: 'pending' | 'paid' | 'failed' | 'cancelled'): Promise<ApiResponse> => {
    return api.put(`/admin/orders/${id}/status`, { payment_status })
  }
}

// 群聊管理API
export interface ChatGroup {
  id: number
  group_name: string
  group_avatar?: string
  description?: string
  created_at: string
  member_count?: number
  members?: Array<{
    user_id: string
    joined_at: string
    nickname?: string
    avatar_url?: string
  }>
}

export interface ChatGroupListParams {
  page?: number
  pageSize?: number
  search?: string
}

export interface CreateChatGroupParams {
  group_name: string
  group_avatar?: string
  description?: string
}

export interface UpdateChatGroupParams {
  group_name?: string
  group_avatar?: string
  description?: string
}

export const chatGroupApi = {
  // 获取群聊列表
  getList: (params: ChatGroupListParams): Promise<PaginatedResponse<ChatGroup>> => {
    return api.get('/admin/chat-groups', { params })
  },

  // 获取群聊详情
  getDetail: (id: number): Promise<ApiResponse<ChatGroup>> => {
    return api.get(`/admin/chat-groups/${id}`)
  },

  // 创建群聊
  create: (params: CreateChatGroupParams): Promise<ApiResponse<ChatGroup>> => {
    return api.post('/admin/chat-groups', params)
  },

  // 更新群聊信息
  update: (id: number, params: UpdateChatGroupParams): Promise<ApiResponse<ChatGroup>> => {
    return api.put(`/admin/chat-groups/${id}`, params)
  },

  // 删除群聊
  delete: (id: number): Promise<ApiResponse> => {
    return api.delete(`/admin/chat-groups/${id}`)
  }
}

// ==================== 消息管理相关接口 ====================

// 消息接口
export interface Message {
  id: string
  group_id: string
  sender_id: string
  message_type: 'text' | 'image' | 'system' | 'demand_card'
  content: string
  created_at: string
  sender?: {
    id: string
    nickname: string
    avatar_url?: string
    phone_number?: string
  }
  group?: {
    id: number
    group_name: string
  }
}

// 消息列表查询参数
export interface MessageListParams {
  page?: number
  pageSize?: number
  messageType?: 'text' | 'image' | 'system' | 'demand_card'
  search?: string
  senderId?: string
}

// 批量删除消息参数
export interface DeleteMessagesParams {
  messageIds: string[]
}

// 消息统计
export interface MessageStats {
  total: number
  today: number
  byType?: {
    text?: number
    image?: number
    system?: number
    demand_card?: number
  }
}

// 消息管理API
export const messageApi = {
  // 获取群聊消息列表
  getGroupMessages: (groupId: number, params?: MessageListParams): Promise<ApiResponse<{data: Message[], pagination: any}>> => {
    return api.get(`/admin/chat-groups/${groupId}/messages`, { params })
  },

  // 获取消息详情
  getDetail: (messageId: string): Promise<ApiResponse<Message>> => {
    return api.get(`/admin/messages/${messageId}`)
  },

  // 删除单条消息
  delete: (messageId: string): Promise<ApiResponse> => {
    return api.delete(`/admin/messages/${messageId}`)
  },

  // 批量删除消息
  batchDelete: (params: DeleteMessagesParams): Promise<ApiResponse<{ deletedCount: number }>> => {
    return api.delete('/admin/messages', { data: params })
  },

  // 获取群聊消息统计
  getGroupStats: (groupId: number): Promise<ApiResponse<MessageStats>> => {
    return api.get(`/admin/chat-groups/${groupId}/messages/stats`)
  }
}

// ==================== 本地服务管理相关接口 ====================

// 本地服务接口
export interface LocalService {
  id: string
  user_id: string
  category_id: number
  title: string
  province?: string
  city?: string
  basic_services?: string
  extended_services?: string
  after_sale_service?: string
  contact_info?: string
  images?: string[]
  status: 'DRAFT' | 'PUBLISHED' | 'OFFLINE'
  audit_status: 'PENDING' | 'APPROVED' | 'REJECTED'
  audit_comment?: string
  audit_time?: string
  auto_publish_at?: string
  deposit_required: number
  deposit_paid: number
  view_count: number
  created_at: string
  updated_at: string
  user?: {
    id: string
    nickname?: string
    phone_number?: string
  }
  category?: {
    id: number
    name: string
  }
}

export interface LocalServiceListParams {
  page?: number
  pageSize?: number
  status?: 'DRAFT' | 'PUBLISHED' | 'OFFLINE'
  audit_status?: 'PENDING' | 'APPROVED' | 'REJECTED'
  search?: string
  province?: string
  city?: string
  category_id?: number
}

export const localServiceApi = {
  // 获取本地服务列表
  getList: (params: LocalServiceListParams): Promise<PaginatedResponse<LocalService>> => {
    return api.get('/admin/local-services', { params })
  },

  // 获取本地服务详情
  getDetail: (id: string): Promise<ApiResponse<LocalService>> => {
    return api.get(`/admin/local-services/${id}`)
  },

  // 更新本地服务状态
  updateStatus: (id: string, status: 'DRAFT' | 'PUBLISHED' | 'OFFLINE'): Promise<ApiResponse> => {
    return api.put(`/admin/local-services/${id}/status`, { status })
  },

  // 删除本地服务
  delete: (id: string): Promise<ApiResponse> => {
    return api.delete(`/admin/local-services/${id}`)
  },

  // 获取待审核列表
  getPendingAudit: (params: LocalServiceListParams): Promise<PaginatedResponse<LocalService>> => {
    return api.get('/admin/local-services/pending-audit', { params })
  },

  // 审核通过
  approve: (id: string, comment?: string): Promise<ApiResponse<LocalService>> => {
    return api.put(`/admin/local-services/${id}/approve`, { comment })
  },

  // 审核拒绝
  reject: (id: string, comment: string): Promise<ApiResponse<LocalService>> => {
    return api.put(`/admin/local-services/${id}/reject`, { comment })
  },

  // 获取审核统计
  getAuditStats: (): Promise<ApiResponse<{
    pending: number
    approved: number
    rejected: number
    total: number
  }>> => {
    return api.get('/admin/local-services/audit-stats')
  }
}

// ==================== 服务分类管理相关接口 ====================

export interface ServiceCategory {
  id: number
  name: string
  icon?: string
  description?: string
  sort_order: number
  is_active: boolean
  created_at: string
  updated_at: string
}

export const serviceCategoryApi = {
  // 获取服务分类列表
  getList: (): Promise<ApiResponse<ServiceCategory[]>> => {
    return api.get('/local-services/categories')
  }
}

// ==================== 曝光台管理相关接口 ====================

export interface ExposurePostListParams {
  page?: number
  pageSize?: number
  search?: string
  startDate?: string
  endDate?: string
  sortBy?: 'created_at' | 'like_count' | 'comment_count'
  sortOrder?: 'asc' | 'desc'
}

export interface UpdateExposurePostParams {
  content: string
  images: string[]
}

export const exposureApi = {
  // 获取曝光台统计信息
  getStats: (): Promise<ApiResponse<ExposureStats>> => {
    return api.get('/admin/exposure/stats')
  },

  // 获取曝光台帖子列表
  getPostsList: (params?: ExposurePostListParams): Promise<ApiResponse<{
    items: ExposurePost[]
    total: number
    page: number
    pageSize: number
  }>> => {
    return api.get('/admin/exposure/posts', { params })
  },

  // 获取单个帖子详情
  getPostDetail: (id: string): Promise<ApiResponse<ExposurePost>> => {
    return api.get(`/admin/exposure/posts/${id}`)
  },

  // 编辑帖子
  updatePost: (id: string, params: UpdateExposurePostParams): Promise<ApiResponse<ExposurePost>> => {
    return api.put(`/admin/exposure/posts/${id}`, params)
  },

  // 删除帖子
  deletePost: (id: string): Promise<ApiResponse> => {
    return api.delete(`/admin/exposure/posts/${id}`)
  },

  // 获取帖子评论列表
  getPostComments: (id: string, params?: { page?: number; pageSize?: number }): Promise<ApiResponse<{
    comments: ExposureComment[]
    pagination: any
  }>> => {
    return api.get(`/admin/exposure/posts/${id}/comments`, { params })
  },

  // 删除评论
  deleteComment: (id: string): Promise<ApiResponse> => {
    return api.delete(`/admin/exposure/comments/${id}`)
  }
}
